package com.chalk.common.util;


import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author xiaoqiang
 * @Description XML工具类
 * @date 2019/1/19 11:46
 */
public class XMLUtil {
    public static Map doXMLParse(String strxml)
            throws IOException, DocumentException {
        strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");
        if ((strxml == null) || ("".equals(strxml))) {
            return null;
        }
        Map m = new HashMap();

        InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
        Document doc = DocumentHelper.parseText(strxml);

        Element root = doc.getRootElement();
        Iterator it = root.elementIterator();
        while (it.hasNext())
        {
            Element e = (Element)it.next();
            String k = e.getName();
            String v = "";
            List children = e.elements();
            if (children.isEmpty()) {
                v = e.getTextTrim();
            } else {
                v = getChildrenText(children);
            }
            m.put(k, v);
        }
        in.close();

        return m;
    }

    public static String getChildrenText(List children)
    {
        StringBuffer sb = new StringBuffer();
        if (!children.isEmpty())
        {
            Iterator it = children.iterator();
            while (it.hasNext())
            {
                Element e = (Element)it.next();
                String name = e.getName();
                String value = e.getTextTrim();
                List list = e.elements();
                sb.append("<" + name + ">");
                if (!list.isEmpty()) {
                    sb.append(getChildrenText(list));
                }
                sb.append(value);
                sb.append("</" + name + ">");
            }
        }
        return sb.toString();
    }
}
